﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BatchRenameFile
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine(Directory.GetCurrentDirectory());
            try
            {
                RenameFiles("Bll", true);
                RenameFiles("Dal", true);
                RenameFiles("Model", false);
                Console.WriteLine("Complete!");
            }
            catch (Exception exception)
            {
                Console.WriteLine("Errer:");
                Console.WriteLine(exception.ToString());
            }
            finally
            {
                Console.ReadKey();
            }
        }

        public static void RenameFiles(string subDir,bool addDir)
        {
            //当前路径
            var curDir = Directory.GetCurrentDirectory();

            if (curDir.Substring(curDir.Length - 1) != "\\")
            {
                curDir = curDir + "\\";
            }

            string srcDir = curDir + subDir;

            string tarDir = curDir + "renamed\\" + subDir+"\\";
            if (!Directory.Exists(srcDir)) return;

            if (!Directory.Exists(tarDir))
            {
                Directory.CreateDirectory(tarDir);
            }

            DirectoryInfo dirInfo = new DirectoryInfo(srcDir);
            foreach (FileInfo fileInfo in dirInfo.GetFiles("*"))
            {
                int point = fileInfo.Name.LastIndexOf('.');
                string file = fileInfo.Name.Substring(0,point);
                string fileExtension = fileInfo.Name.Substring(point);
                string fileName = GetFirstUpperString(file);
                fileName = addDir ? fileName + subDir + fileExtension : fileName + fileExtension;
                CopyFile(fileInfo.FullName, tarDir + fileName);
            }
        }


        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="srcFile"></param>
        /// <param name="tarFile"></param>
        private static void CopyFile(string srcFile, string tarFile)
        {
            try
            {
                if (!File.Exists(srcFile)) return;

                if (File.Exists(tarFile))
                {
                    File.Delete(tarFile);
                }
               
                File.Copy(srcFile, tarFile);
                
            }
            catch (Exception exception)
            {
                throw exception;
            }
        }


        private static string GetFirstUpperString(string src)
        {
            if (string.IsNullOrEmpty(src)) return "";
            string strTmp = src.Replace("_", "");

            return strTmp.Substring(0, 1).ToUpper() + strTmp.Substring(1);
        }
    }
}
